package cn.com.nes.common.util.tree;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class TreeBuilder<T extends TreeNode<T>> {

    /**
     * 递归树
     * @param nodeList
     * @return
     */
    public List<T> buildTree(List<T> nodeList){
        if (CollUtil.isEmpty(nodeList)) {
            return Collections.emptyList();
        }
        List<T> parentList= nodeList.stream().filter(a -> StrUtil.isEmpty(a.getParentId())).collect(Collectors.toList());
        for (T parentNode : parentList) {
            parentNode.setChildren(getChild(parentNode.getId(), nodeList));
        }
        return parentList;
    }

    /**
     *
     * @param rootNodeId 根节点id
     * @param nodeList  全部菜单项
     * @return
     * 获取一个根节点菜单的树结构
     */
    public List<T> getChild(String rootNodeId, List<T> nodeList) {
        // 子菜单
        List<T> childList = new ArrayList<>();
        for (T node : nodeList) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (StrUtil.isNotBlank(node.getParentId())) {
                if (node.getParentId().equals(rootNodeId)) {
                    childList.add(node);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (T node : childList) {
            //type是0的是非终节点
            if (!node.getLeaf()) {
                // 递归
                node.setChildren(getChild(node.getId(), nodeList));
            }
            //排序
            if (CollUtil.isNotEmpty(node.getChildren())){
                List<T> childrenList= new ArrayList<>(node.getChildren());
                node.setChildren(childrenList);
            } else {
                node.setLeaf(true);
            }
        } // 递归退出条件
        if (childList.isEmpty()) {
            return Collections.emptyList();
        }
        //再次排序
        return new ArrayList<>(childList);
    }

}


